from PySide6.QtCore import QThread, Signal, Qt
from PySide6.QtWidgets import *
from PySide6.QtGui import QResizeEvent

from common import ImgExtractThread
from ..base import TableFrameBase, ReturnView
from qfluentwidgets import StateToolTip, TransparentToolButton, FluentIcon, InfoBar, TitleLabel
from components import OpenFileDialog
from tools import FileInformation


class ImgExtractFrame(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.stateToolTip = StateToolTip('Image Extract', '正在提取 Word 文档中的图片，请稍后...', self)
        self.stateToolTip.hide()

        self.table = TableFrameBase()
        self.table.setHeaders(['名称', '完整路径', '创建日期', '类型', '大小'])
        self.table.setTitle("Word 文档图片提取")

        self.imgThread = ImgExtractThread(self)

        self.vBox.addWidget(self.returnButton, 0, Qt.AlignmentFlag.AlignLeft)
        self.vBox.addWidget(self.table)
        self.initEvent()

    def initEvent(self):
        # 按钮事件
        self.returnButton.clicked.connect(self.return_event)
        self.table.started.connect(self.started_button_event)
        self.table.added.connect(self.openFile)
        self.table.saved.connect(self.openDir)
        # 线程事件
        self.imgThread.started.connect(self.stateToolTip.show)
        self.imgThread.error.connect(self.error_thread)
        self.imgThread.finished.connect(self.finished_thread)

    def started_button_event(self):
        column = self.table.getColumnValues(1)
        if len(column) == 0:
            InfoBar.warning('提示', '请选择Word文件', parent=self.parent())
            return False

        saveFile = self.table.lineText()
        if saveFile is False:
            return

        self.imgThread.set_value(column, saveFile)
        self.imgThread.start()

    def error_thread(self, msg):
        InfoBar.error('错误', msg, parent=self, duration=10000)

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('提示', '图片提取完毕', duration=3000, parent=self)

    def openFile(self):
        files = OpenFileDialog(self).getOpenFileNames(filter='word文档(*.doc;*.docx);;dox(*.doc);;docx(*.docx)')
        for file in files[0]:
            if file in self.table.getColumnValues(1):
                InfoBar.warning('提示', file + ' 已存在', parent=self)
                continue
            fp = FileInformation(file)
            self.table.addItem([fp.name(), file, fp.st_ctime(), fp.suffix(), fp.size()])

    def openDir(self):
        file = OpenFileDialog(self).getExistingDirectory()
        self.table.setLineText(file)

    def return_event(self):
        self.table.clear()
        self.returned.emit()

    def resizeEvent(self, event: QResizeEvent):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)
